package com.jacken.springcloudseatabank01.service.impl;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jacken.springcloudseatabank01.common.Constant;
import com.jacken.springcloudseatabank01.common.exception.BizException;
import com.jacken.springcloudseatabank01.entity.AccountInfo;
import com.jacken.springcloudseatabank01.entity.basic.Result;
import com.jacken.springcloudseatabank01.feign.BankFeignClient;
import com.jacken.springcloudseatabank01.mapper.AccountInfoMapper;
import com.jacken.springcloudseatabank01.service.IAccountService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @author wangqiang
 * @version 1.0
 * @date 2020/10/8 9:30
 */
@Service
public class IAccountServiceImpl extends ServiceImpl<AccountInfoMapper, AccountInfo> implements IAccountService {


    @Resource
    private AccountInfoMapper accountInfoMapper;

    @Resource
    private BankFeignClient bankFeignClient;

    /**
     * 更新账户金额
     *
     * @param accountNo      账户
     * @param accountBalance 金额
     */
    @Override
    @GlobalTransactional//开启全局事务
    @Transactional  //开启本地事务
    public void updateAccountBalance(String accountNo, String otherAccountNo, Double accountBalance) {
        System.out.println("xid===>"+RootContext.getXID());
        //1 扣减张三的钱
        int i = accountInfoMapper.updateAccountBalance(accountNo, accountBalance * (-1));
        if (i > 0) {
            //2 远程调用增加李四的钱
            Result result = bankFeignClient.transfer(otherAccountNo, accountBalance);
            if (result.getMessage().equals(Constant.TRANSFER_FAIL_MESSAGE)) {
                throw new BizException(Constant.TRANSFER_FAIL_MESSAGE);
            }
        }
    }
}
